<template>
    <div class="body">
        <div style="font-size: 30px">查询贡献者 状态：{{ state }}</div>
        <div style="font-size: 24px;margin: 0 auto">
            <el-link type="primary" href="https://gitee.com/LLLLLLin/openharmony_commit" style="margin-right: 10px"
                     slot="reference">代码仓库地址
            </el-link>
            <el-link type="primary" href="https://gitee.com/api/v5/swagger#/getV5ReposOwnerRepoStargazers?ex=no"
                     style="margin-right: 10px" slot="reference">gitee文档
            </el-link>

        </div>
        <div class="flex-between" style="font-size: 24px">
            配置1
        </div>
        <div class="flex-between">
            <el-popover
                placement="top-start"
                title="token获取"
                width="200"
                trigger="hover"
                content="访问https://gitee.com/api/v5/swagger#/getV5OrgsOrgRepos 后,点击右上角申请授权，授权后access_token一栏即可看到">
                <el-link type="primary" style="margin-right: 10px" slot="reference">token:</el-link>
            </el-popover>

            <el-input v-model="token" placeholder="请输入token" style="width: 200px;flex-grow: 1"></el-input>
            <div style="margin: 0 10px">时间：</div>
            <el-date-picker
                value-format="yyyy-MM-dd"
                v-model="date"
                type="date"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期">
            </el-date-picker>
        </div>
        <div class="flex-between">
            <div>请选择org组织（多选，右侧可新增组织）:</div>
            <el-input placeholder="新增组织" v-model="orgInput" style="width: 200px">
                <el-button slot="append" icon="el-icon-plus" @click="addOrg"></el-button>
            </el-input>
        </div>
        <div class="flex-between">
            <el-checkbox-group v-model="selectedOrg">
                <el-checkbox-button v-for="org in orgOptions" :label="org" :key="org">{{ org }}</el-checkbox-button>
            </el-checkbox-group>
            <el-button type="warning" style="margin-left: 10px" @click="clearOrg">重置</el-button>
        </div>
        <div class="flex-row">
            上传excel文件,重置大厂名单（当前已内置名单）
        </div>
        <div class="flex-row">
            <el-upload
                style="margin: 0 10px"
                ref="upload"
                class="upload-demo"
                action="/"
                :show-file-list="false"
                :auto-upload="false"
                :on-change="importDaChangList">
                <el-button type="primary">上传大厂名单：{{ daChangList.length }}（列名：email,name）</el-button>
            </el-upload>
        </div>
        <div class="flex-row">
            选择PR状态
        </div>
        <div class="flex-row">
            <el-select v-model="prStateVM" placeholder="请选择">
                <el-option
                    v-for="item in prOptions"
                    :key="item"
                    :label="item"
                    :value="item">
                </el-option>
            </el-select>
        </div>
        <el-divider></el-divider>
        <div class="flex-between" style="font-size: 24px">
            操作
        </div>

        <div class="flex-row">
            <el-button type="primary" @click="getRepo" :disabled="isLoadingRepo"> 1.根据组织获取仓库: {{ repos.length }}
            </el-button>
            <el-button type="primary" @click="getPR" :disabled="isLoadingCommit">
                2. 获取PR:{{ prList.length }}
            </el-button>
            <el-button type="primary" @click="getCommits" :disabled="isLoadingPR">
                3. 获取PR下所有提交:{{ commitList.length }}
            </el-button>
            <el-button type="primary" @click="getCommitter" :disabled="isLoadingCommit">
                4. 获取所有committer
            </el-button>
            <!--            &lt;!&ndash;    导入excel并读取解析    &ndash;&gt;-->
            <!--            <el-upload-->
            <!--                style="margin: 0 10px"-->
            <!--                ref="upload"-->
            <!--                class="upload-demo"-->
            <!--                action="/"-->
            <!--                :show-file-list="false"-->
            <!--                :auto-upload="false"-->
            <!--                :on-change="importExcel">-->
            <!--                <el-button type="primary">4. 上传表格,过滤掉表格中的邮箱（列名为committerEmail）</el-button>-->
            <!--            </el-upload>-->
            <!--            <el-button type="primary" @click="filterImportExcelList" :disabled="isLoadingCommit">-->
            <!--                5. 过滤数据-->
            <!--            </el-button>-->
        </div>
        <div class="flex-row">
            <el-button icon="el-icon-download" type="info"
                       @click="exportExcel(allCommitterList,'所有提交者' + allCommitterList.length)">
                所有提交者:{{ allCommitterList.length }}
            </el-button>
            <el-button icon="el-icon-download" type="info"
                       @click="exportExcel(daChangCommitterList,'大厂提交者' + daChangCommitterList.length)">
                大厂提交者:{{ daChangCommitterList.length }}
            </el-button>
            <el-button icon="el-icon-download" type="info"
                       @click="exportExcel(knowledgeCommitterList,'知识体系提交过' + knowledgeCommitterList.length)">
                知识体系提交过:{{ knowledgeCommitterList.length }}
            </el-button>
            <el-button icon="el-icon-download" type="info"
                       @click="exportExcel(noKnowledgeCommitterList,'非知识体系提交过' + noKnowledgeCommitterList.length)">
                非知识体系提交过:{{ noKnowledgeCommitterList.length }}
            </el-button>
            <el-button icon="el-icon-download" type="info"
                       @click="exportExcel(repeatCommitterList,'知识体系内外均有提交' + repeatCommitterList.length)">
                知识体系内外均有提交:{{ repeatCommitterList.length }}
            </el-button>
            <el-button icon="el-icon-download" type="info"
                       @click="exportExcel(onlyKnowledgeCommitterList,'只在知识体系提交' + onlyKnowledgeCommitterList.length)">
                只在知识体系提交:{{ onlyKnowledgeCommitterList.length }}
            </el-button>
        </div>
        <div class="flex-between" style="font-size: 24px">
            过滤后的数据
        </div>
        <div class="flex-row">
            <el-button icon="el-icon-download" type="warning"
                       @click="exportExcel(filteredAllCommitterList,'所有提交者_过滤后新增数据' + filteredAllCommitterList.length)">
                所有提交者:{{ filteredAllCommitterList.length }}
            </el-button>
            <el-button icon="el-icon-download" type="warning"
                       @click="exportExcel(filteredDaChangCommitterList,'大厂提交者_过滤后新增数据' + filteredDaChangCommitterList.length)">
                大厂提交者:{{ filteredDaChangCommitterList.length }}
            </el-button>
            <el-button icon="el-icon-download" type="warning"
                       @click="exportExcel(filteredKnowledgeCommitterList,'知识体系提交过_过滤后新增数据' + filteredKnowledgeCommitterList.length)">
                知识体系提交过:{{ filteredKnowledgeCommitterList.length }}
            </el-button>
            <el-button icon="el-icon-download" type="warning"
                       @click="exportExcel(filteredNoKnowledgeCommitterList,'非知识体系提交过_过滤后新增数据' + filteredNoKnowledgeCommitterList.length)">
                非知识体系提交过:{{ filteredNoKnowledgeCommitterList.length }}
            </el-button>
            <el-button icon="el-icon-download" type="warning"
                       @click="exportExcel(filteredRepeatCommitterList,'知识体系内外均有提交_过滤后新增数据' + filteredRepeatCommitterList.length)">
                知识体系内外均有提交:{{ filteredRepeatCommitterList.length }}
            </el-button>
            <el-button icon="el-icon-download" type="warning"
                       @click="exportExcel(filteredOnlyKnowledgeCommitterList,'只在知识体系提交_过滤后新增数据' + filteredOnlyKnowledgeCommitterList.length)">
                只在知识体系提交:{{ filteredOnlyKnowledgeCommitterList.length }}
            </el-button>
        </div>
        <div class="flex-row">
            <el-button type="primary" @click="showFormula">
                计算公式
            </el-button>
            <el-button type="primary" @click="showKPIData">
                计算各组数据
            </el-button>
            <el-button type="primary" @click="showKPIFilterData">
                计算过滤后各组数据
            </el-button>
        </div>
        <div class="flex-between" style="font-size: 24px">
            其他
        </div>
        <div class="flex-row">
            <el-button type="success" icon="el-icon-download"
                       @click="exportPRExcel(prList,'导出所有PR信息' + prList.length)">导出PR
            </el-button>
            <el-button type="success" icon="el-icon-download"
                       @click="exportExcel(commitList,'导出所有提交信息' + commitList.length)">导出所有提交信息
            </el-button>
            <el-button type="success" icon="el-icon-download" style="margin:0 10px" @click="exportExcelByGroup">
                分页导出所有提交信息
            </el-button>
        </div>
        <div class="flex-row">
            <el-input
                style="margin: 0 10px;width: 400px"
                placeholder="过滤邮箱"
                prefix-icon="el-icon-search"
                v-model="filterEmail">
            </el-input>
            <el-button type="primary" @click="getFilterEmailCommits">
                1. 获取过滤邮箱后的提交:{{ filterEmailCommits.length }}
            </el-button>
            <el-button type="success" icon="el-icon-download"
                       @click="exportExcel(filterEmailCommits,'指定邮箱的提交' + filterEmailCommits.length)">
                2. 获取过滤邮箱后的提交:{{ filterEmailCommits.length }}
            </el-button>
        </div>
        <div class="flex-row">
            <el-input
                style="margin: 0 10px;width: 400px"
                placeholder="过滤PR标题"
                prefix-icon="el-icon-search"
                v-model="filterPRTitle">
            </el-input>
            <el-button type="primary" @click="getFilterPRTitleCommits">
                1. 获取过滤PR标题后的提交:{{ filterPRTitleCommits.length }}
            </el-button>
            <el-button type="success" icon="el-icon-download"
                       @click="exportExcel(filterPRTitleCommits,'指定邮箱的提交' + filterPRTitleCommits.length)">
                2. 获取过滤PR标题后的提交:{{ filterPRTitleCommits.length }}
            </el-button>
        </div>
    </div>
</template>

<script>

import export_json_to_excel from "../excel/Export2Excel";

import FileSaver from 'file-saver';
import * as XLSX from 'xlsx'

export default {
    name: 'OHAndSig',
    data() {
        return {
            token: '0fd1e29a051ab8f564ca7486ba5fb5cc',
            selectedOrg: ['OpenHarmony', 'OpenHarmony-SIG', 'OpenHarmony-TPC'],
            orgOptions: ['OpenHarmony', 'OpenHarmony-SIG', 'OpenHarmony-TPC'],
            prOptions: ['all', 'open', 'closed', 'merged'],
            prStateVM: 'merged',
            orgInput: '',
            date: '',
            repos: [],
            isLoadingRepo: false,
            commitList: [],
            prList: [],
            isLoadingPR: false,
            isLoadingCommit: false,
            state: '等待中',
            statsCount: 0,// 已添加修改行数字段的commit数量
            maxQuest: 200,// 请求修改行数时，最大请求数
            isLoadingStat: false,
            knowledgeWhiteSet: new Set(['knowledge', 'knowledge_demo_smart_home', 'knowledge_demo_temp', 'knowledge_demo_entainment',
                'knowledge_demo_shopping', 'knowledge_demo_travel', 'app_sample', 'vendor_oh_fun']),
            // 大厂数据
            daChangList: [
                {
                    "email": "@hoperun.com",
                    "name": "润和"
                },
                {
                    "email": "@chinasoftinc.com",
                    "name": "中软国际"
                },
                {
                    "email": "@midea.com",
                    "name": "美的"
                },
                {
                    "email": "@jd.com",
                    "name": "京东"
                },
                {
                    "email": "pateo.com.cn",
                    "name": "博泰车联网"
                },
                {
                    "email": "@ecarxgroup.com",
                    "name": "亿咖通科技"
                },
                {
                    "email": "@talkweb.com.cn",
                    "name": "拓维信息"
                },
                {
                    "email": "shineweng.com",
                    "name": "仙翁科技"
                },
                {
                    "email": "droi.com",
                    "name": "卓易科技"
                },
                {
                    "email": "newlandcomputer.com",
                    "name": "新大陆"
                },
                {
                    "email": "@kaihongdigi.com",
                    "name": "深开鸿"
                },
                {
                    "email": "@isoftstone.com",
                    "name": "软通"
                },
                {
                    "email": "@chipsea.com",
                    "name": "芯海科技"
                },
                {
                    "email": "@urovo.com",
                    "name": "优博讯"
                },
                {
                    "email": "xdf.com",
                    "name": "东方创科"
                },
                {
                    "email": "szzt.com.cn",
                    "name": "证通电子"
                },
                {
                    "email": "@thundersoft.com",
                    "name": "中科创达"
                },
                {
                    "email": "@neusoft.com",
                    "name": "东软集团"
                },
                {
                    "email": "@superred.com.cn",
                    "name": "万里红科技"
                },
                {
                    "email": "@unionman.com.cn",
                    "name": "九联科技"
                },
                {
                    "email": "@archermind.com",
                    "name": "诚迈科技"
                },
                {
                    "email": "elecfans.com",
                    "name": "华秋电路"
                },
                {
                    "email": "speedatagroup.com",
                    "name": "思必拓科技"
                },
                {
                    "email": "@iscas.ac.cn",
                    "name": "中国科学院软件研究所"
                },
                {
                    "email": "@ingenic.com",
                    "name": "君正集团"
                },
                {
                    "email": "@goodix.com",
                    "name": "汇顶科技"
                },
                {
                    "email": "@nj.iscas.ac.cn",
                    "name": "中科南京软件技术研究所"
                },
                {
                    "email": "@bearpi.cn",
                    "name": "小熊派"
                },
                {
                    "email": "@digitalchina.com",
                    "name": "神州数码"
                },
                {
                    "email": "@allwinnertech.com",
                    "name": "全志"
                },
                {
                    "email": "@starfivetech.com",
                    "name": "赛昉科技"
                },
                {
                    "email": "@chinatelecom.cn",
                    "name": "天翼物联"
                },
                {
                    "email": "xlx-ele.com",
                    "name": "芯联芯"
                },
                {
                    "email": "@lejurobot.com",
                    "name": "乐聚"
                },
                {
                    "email": "@comtech.com.cn",
                    "name": "科通技术"
                },
                {
                    "email": "@bestechnic.com",
                    "name": "恒玄科技"
                },
                {
                    "email": "@kotei-info.com",
                    "name": "光庭信息"
                },
                {
                    "email": "@lango-tech.cn",
                    "name": "朗国"
                },
                {
                    "email": "@holdiot.com",
                    "name": "厚德物联网"
                },
                {
                    "email": "@kikatech.com",
                    "name": "新美互通"
                },
                {
                    "email": "@bekencorp.com",
                    "name": "博通集成电路"
                },
                {
                    "email": "@hyperchain.cn",
                    "name": "趣链科技"
                },
                {
                    "email": "@fn-link.com",
                    "name": "欧智通"
                },
                {
                    "email": "@billjc.com",
                    "name": "佰钧成"
                },
                {
                    "email": "@nucleisys.com",
                    "name": "芯来科技"
                },
                {
                    "email": "@rock-chips.com",
                    "name": "瑞芯微"
                },
                {
                    "email": "@vyagoo.com",
                    "name": "研果科技"
                },
                {
                    "email": "@dt4sw.com",
                    "name": "狄泰软件"
                },
                {
                    "email": "@realsil.com.cn",
                    "name": "瑞晟"
                },
                {
                    "email": "@malata.com",
                    "name": "万利达"
                },
                {
                    "email": "@fzlzdz.com",
                    "name": "福州市凌睿智捷电子有限公司"
                },
                {
                    "email": "@hiharmonica.com",
                    "name": "深鸿会"
                },
                {
                    "email": "@snqu.com",
                    "name": "盛趣"
                },
                {
                    "email": "@tes-tec.com",
                    "name": "宸展光电"
                },
                {
                    "email": "@xgimi.com",
                    "name": "极米"
                },
                {
                    "email": "@geohey.com",
                    "name": "极海"
                },
                {
                    "email": "@asrmicro.com",
                    "name": "翱捷科技"
                },
                {
                    "email": "@hawaiiantel.net",
                    "name": "道客"
                }, {
                    "email": "@kaihong.com",
                    "name": "深开鸿"
                }, {
                    "email": "@telink-semi.com",
                    "name": "泰凌微电子"
                },{
                    "email": "@ub-tech.cn",
                    "name": "优博终端"
                },{
                    "email": "@sinux.com.cn",
                    "name": "合讯科技"
                },{
                    "email": "@runkaihong.com",
                    "name": "润开鸿"
                }
            ],
            daChangCommitterMap: new Map(),
            knowledgeCommitterMap: new Map(),
            noKnowledgeCommitterMap: new Map(),
            repeatCommitterList: [],// 上面两个的交集
            knowledgeCommitterList: [],
            noKnowledgeCommitterList: [],
            onlyKnowledgeCommitterList: [],
            daChangCommitterList: [],
            allCommitterList: [],
            allCommitterMap: new Map(),
            importExcelList: [], // 导入的excel数据
            // 过滤后的数据
            filteredRepeatCommitterList: [],
            filteredKnowledgeCommitterList: [],
            filteredNoKnowledgeCommitterList: [],
            filteredOnlyKnowledgeCommitterList: [],
            filteredDaChangCommitterList: [],
            filteredAllCommitterList: [],
            // 过滤邮箱
            filterEmail: '',
            filterEmailCommits: [],
            filterPRTitle: '',
            filterPRTitleCommits: []
        }
    },
    mounted() {
        this.initAxios()
        this.inDaChangList()
    },
    methods: {
        initAxios() {
            // 设置跨域请求头
            this.axios.defaults.headers.common['Access-Control-Allow-Origin'] = "*"

            this.axios.interceptors.response.use(
                response => {
                    // 如果返回的状态码为200，说明接口请求成功，可以正常拿到数据
                    // 否则的话抛出错误
                    if (!response) {
                        console.error("404不做处理")
                        return
                    }
                    if (response && response.status === 200) {
                        return Promise.resolve(response);
                    } else {
                        return Promise.reject(response);
                    }
                },

                error => {
                    if (error && error.config.headers.isRelease) {
                        console.warn("错误请求不拦截：" + error.config.url)
                        return Promise.resolve(error);
                    } else {
                        let msg = ''
                        if (error && error.status && error.response.status) {
                            msg = error.response.status
                        }
                        this.$message.error('请求出错，点击F12进入控制台查看详情：' + msg)
                        console.error(error)
                        return Promise.reject(error);
                    }

                }
            );
        },
        inDaChangList() {
            this.daChangList.forEach(item => {
                item.email = item.email.replace("@", "").toLowerCase()
            });
        },
        addOrg() {
            this.orgOptions.push(this.orgInput)
        },
        clearOrg() {
            this.orgOptions = ['openharmony', 'OpenHarmony-SIG', 'OpenHarmony-TPC']
        },
        async getRepo() {
            try {
                this.isLoadingRepo = true
                this.repos = []
                for (let i = 0; i < this.selectedOrg.length; i++) {
                    let org = this.selectedOrg[i]
                    await this.getRepoByOrg(org)
                }
                this.state = 'repo 获取完毕'
            } catch (e) {
                this.state = 'repo 获取失败 F12控制台查看错误'
                console.error(e)
            } finally {
                this.isLoadingRepo = false
            }
        },
        async getRepoByOrg(org) {
            // 获取openharmony下public仓库中
            this.state = '获取openharmony下public仓库中'
            let page = 0
            let totalPage = 0
            const count = 100
            try {
                do {
                    page++
                    let response = await this.axios.get(`https://gitee.com/api/v5/orgs/${org}/repos?access_token=${this.token}&type=public&page=${page}&per_page=${count}`)
                    if (!totalPage) {
                        totalPage = response.headers.total_page
                    }
                    response.data.forEach(item => {
                        this.repos.push({org: org, path: item.path})
                    })

                } while (page < totalPage)
            } catch (e) {
                this.$message.error('获取仓库失败F12控制台查看详情')
                console.error('获取仓库失败')
                console.error(e)
            }
            console.log(`获取${org}所有public仓库完毕`)
            console.log('repos：')
            console.log(this.repos)

        },
        getPR() {
            if (this.date.length == 0) {
                this.$message.warning('不选择起始时间默认搜索全部')
            }
            this.$notify({
                title: '成功',
                message: '开始获取所有提交，为加快获取速度，需自行关注按钮中的提交数是否不再增加了，若有报错注意在F12控制台中进行查看是否可忽略',
                type: 'success'
            });
            let since = this.date
            try {
                this.isLoadingPR = true
                this.prList = []
                for (let i = 0; i < this.repos.length; i++) {
                    let repo = this.repos[i].path
                    let org = this.repos[i].org
                    let page = 1
                    const maxPageCount = 100
                    let url = `https://gitee.com/api/v5/repos/${org}/${repo}/pulls?access_token=${this.token}&state=${this.prStateVM}&sort=created&since=${since}&direction=desc&page=${page}&per_page=${maxPageCount}`
                    this.axios.get(url)
                        .then(async response1 => {
                            if (!response1 || !response1.data) {
                                console.warn(response1)
                                return
                            }
                            response1.data.map(item => {
                                this.setPRList(org, repo, item)
                            })

                            while (response1.data.length >= maxPageCount) {
                                page++
                                let url = `https://gitee.com/api/v5/repos/${org}/${repo}/pulls?access_token=${this.token}&state=${this.prStateVM}&sort=created&since=${since}&direction=desc&page=${page}&per_page=${maxPageCount}`
                                response1 = await this.axios.get(url)
                                response1.data.map(item => {
                                    this.setPRList(org, repo, item)
                                })
                                // console.log('第' + page + '页：' + response1.data.length + ' ' + url)
                            }
                        })
                }

            } catch (e) {
                this.state = 'getPR 失败'
                console.error(e)

            } finally {
                this.isLoadingPR = false
                console.log("prList ", this.prList)
                this.prList.forEach(item=>{
                    if (item.prState !== this.prStateVM && this.prStateVM !== "all"){
                        console.error("该PR状态异常", this.prList)
                    }
                })
            }
        },


        setPRList(org, repo, item) {
            let obj = {
                org: org,
                repo: repo,
                prNumber: item.number,
                prState: item.state,
                prUrl: item.url,
                prHtmlUrl: item.html_url,
                prTitle: item.title,
                prCreateDate: item.created_at,
            }
            this.prList.push(obj)
        },

        // 20个请求并发
        // async getCommits() {
        //     // let obj = {
        //     //     org: 'OpenHarmony',
        //     //     repo: 'kernel_liteos_m',
        //     //     prNumber: '738',
        //     //     prState: 'item.state',
        //     //     prUrl: 'item.url',
        //     //     prHtmlUrl: 'item.html_url'
        //     // }
        //     // this.prList = [obj,obj,obj,obj,obj,obj,obj,obj,obj,obj,obj,obj,obj,obj,obj,obj,obj,obj,obj,obj,obj,obj,]
        //     if (this.prList.length == 0) {
        //         this.$message.error('请获取PR先')
        //         return
        //     }
        //     this.$notify({
        //         title: '成功',
        //         message: '开始获取所有提交，为加快获取速度，需自行关注按钮中的提交数是否不再增加了，若有报错注意在F12控制台中进行查看是否可忽略',
        //         type: 'success'
        //     });
        //     try {
        //         this.isLoadingCommit = true
        //         this.commitList = []
        //         const maxRequestCount = 20;
        //         let requests = []
        //         for (let i = 0; i < this.prList.length; i++) {
        //             if (requests.length >= maxRequestCount) {
        //                 try {
        //                     let responseList = await this.axios.all(requests)
        //                     responseList.forEach(response1 => {
        //                         let i = response1.config.data
        //                         if (!response1 || !response1.data) {
        //                             console.warn(response1)
        //                             let obj = {
        //                                 org: this.prList[i].org,
        //                                 repo: this.prList[i].repo,
        //                                 prState: 'pr或仓库 异常 ' + this.prList[i].prState,
        //                                 prUrl: this.prList[i].prUrl,
        //                                 prHtmlUrl: this.prList[i].prHtmlUrl,
        //                                 prTitle: this.prList[i].prTitle,
        //                                 prCreateDate: this.prList[i].prCreateDate,
        //                             }
        //                             this.commitList.push(obj)
        //                         } else {
        //                             response1.data.map(item => {
        //                                 this.pushCommitList(this.prList[i], item)
        //                             })
        //                         }
        //                     })
        //                 } catch (err) {
        //                     console.error("responseList", arguments)
        //                 }
        //                 requests = []
        //             }
        //             let repo = this.prList[i].repo
        //             let org = this.prList[i].org
        //             let prNumber = this.prList[i].prNumber
        //             let url = `https://gitee.com/api/v5/repos/${org}/${repo}/pulls/${prNumber}/commits?access_token=${this.token}`
        //             requests.push(this.axios.get(url, {
        //                 headers: {
        //                     "isRelease": true,
        //                     "prIndex": i,
        //                 },
        //                 data: i
        //             }))
        //         }
        //         if (requests.length > 0) {
        //             try {
        //                 let responseList = await this.axios.all(requests)
        //                 responseList.forEach(response1 => {
        //                     let i = response1.config.data
        //                     if (!response1 || !response1.data) {
        //                         console.warn(response1)
        //                         let obj = {
        //                             org: this.prList[i].org,
        //                             repo: this.prList[i].repo,
        //                             prState: 'pr或仓库 异常 ' + this.prList[i].prState,
        //                             prUrl: this.prList[i].prUrl,
        //                             prHtmlUrl: this.prList[i].prHtmlUrl,
        //                             prTitle: this.prList[i].prTitle,
        //                             prCreateDate: this.prList[i].prCreateDate,
        //                         }
        //                         this.commitList.push(obj)
        //                     } else {
        //                         response1.data.map(item => {
        //                             this.pushCommitList(this.prList[i], item)
        //                         })
        //                     }
        //                 })
        //             } catch (err) {
        //                 console.error("responseList", arguments)
        //             }
        //             requests = []
        //         }
        //     } catch (e) {
        //         this.state = 'getCommits 失败'
        //         console.error(e)
        //
        //     } finally {
        //         this.isLoadingCommit = false
        //     }
        // },

        // 同步
        async getCommits() {
            // let obj = {
            //     org: 'OpenHarmony',
            //     repo: 'kernel_liteos_m',
            //     prNumber: '737',
            //     prState: 'item.state',
            //     prUrl: 'item.url',
            //     prHtmlUrl: 'item.html_url'
            // }
            // this.prList = [obj, obj, obj, obj, obj, obj, obj, obj, obj, obj, obj, obj, obj, obj, obj, obj, obj, obj, obj, obj, obj, obj,]
            // if (this.prList.length == 0) {
            //     this.$message.error('请获取PR先')
            //     return
            // }
            console.log("prList ", this.prList)
            this.prList.forEach(item=>{
                if (item.prState !== this.prStateVM && this.prStateVM !== "all"){
                    console.error("该PR状态异常", this.prList)
                }
            })
            try {
                this.isLoadingCommit = true
                this.commitList = []
                for (let i = 0; i < this.prList.length; i++) {
                    let repo = this.prList[i].repo
                    let org = this.prList[i].org
                    let prNumber = this.prList[i].prNumber
                    let url = `https://gitee.com/api/v5/repos/${org}/${repo}/pulls/${prNumber}/commits?access_token=${this.token}`
                    try {
                        let response = await this.axios.get(url)
                        if (!response || !response.data) {
                            console.warn(response)
                            let obj = {
                                org: this.prList[i].org,
                                repo: this.prList[i].repo,
                                prState: 'pr或仓库 异常 ' + this.prList[i].prState,
                                prNumber: this.prList[i].prNumber,
                                prUrl: this.prList[i].prUrl,
                                prHtmlUrl: this.prList[i].prHtmlUrl,
                                prTitle: this.prList[i].prTitle,
                                prCreateDate: this.prList[i].prCreateDate,
                            }
                            this.commitList.push(obj)
                        } else {
                            response.data.map(item => {
                                this.pushCommitList(this.prList[i], item)
                            })
                        }
                    } catch (e) {
                        console.error("pr获取提交出错",url)
                    }
                }
            } catch (e) {
                this.state = 'getCommits 失败'
                console.error(e)

            } finally {
                this.isLoadingCommit = false
            }
        },

        pushCommitList(prData, item) {
            // 设置大厂数据
            let isDaChang = false
            let daChangName = ''
            let email = item.commit.committer.email.toLowerCase()
            // 规避gitee的bug
            if (email === 'noreply@gitee.com') {
                email = item.commit.author.email.toLowerCase()
            }

            let daChangData = this.daChangList.find(item => {
                return email.includes(item.email.toLowerCase())
            });
            if (daChangData) {
                isDaChang = true
                daChangName = daChangData.name
            }

            let org = prData.org
            let repo = prData.repo

            // 存在author为null情况
            let authorUrl = ""
            if (!item.author || !item.author.html_url){
                authorUrl = ""
            }else {
                authorUrl = item.author.html_url
            }

            let obj = {
                org: prData.org,
                repo: prData.repo,
                prState: prData.prState,
                prUrl: prData.prUrl,
                prHtmlUrl: prData.prHtmlUrl,
                prNumber: prData.prNumber,
                prTitle: prData.prTitle,
                prCreateDate: prData.prCreateDate,

                commitHtmlUrl: item.html_url,
                commitUrl: item.url,
                authorName: item.commit.author.name,
                authorEmail: item.commit.author.email,
                authorDate: item.commit.author.date,
                authorUrl: authorUrl,
                committerName: item.commit.committer.name,
                committerEmail: email,
                committerDate: item.commit.committer.date,
                isDaChang: isDaChang,
                daChangName: daChangName,
            }
            // 设置知识体系工作组数据 和 大厂数据
            if (!isDaChang) {
                if (org == 'OpenHarmony-TPC' || this.knowledgeWhiteSet.has(repo)) {
                    this.knowledgeCommitterMap.set(email, obj)
                } else {
                    this.noKnowledgeCommitterMap.set(email, obj)
                }
            } else {
                this.daChangCommitterMap.set(email, obj)
            }
            // 获取所有提交者信息
            this.allCommitterMap.set(email, obj)

            if (item.commit.message.length > 10000) {
                let msg = '(数据过长已截取)' + item.commit.message.substring(0, 10000) + '(数据过长已截取)'
                obj.committerMessage = msg
            } else {
                obj.committerMessage = item.commit.message
            }
            this.commitList.push(obj)
        },
        //导出的方法
        exportExcel(exportList, exportName) {
            const tHeader = ["org", "repo", "commitHtmlUrl", "commitUrl", "prNumber", "prState", "prUrl", "prHtmlUrl", "prTitle", "prCreateDate", "authorName", "authorEmail", "authorDate", "authorUrl", "committerName", "committerEmail", "committerDate", "isDaChang", "daChangName", "additions", "deletions", "total"]
            // 上面设置Excel的表格第一行的标题
            // const filterVal = ["operationName", "operationType", "operationDate",'operationMsg'];
            const filterVal = ["org", "repo", "commitHtmlUrl", "commitUrl", "prNumber", "prState", "prUrl", "prHtmlUrl", "prTitle", "prCreateDate", "authorName", "authorEmail", "authorDate","authorUrl", "committerName", "committerEmail", "committerDate", "isDaChang", "daChangName", "additions", "deletions", "total"]
            // 上面的index、nickName、name是tableData里对象的属性
            const list = exportList; //把data里的tableData存到list
            const data = this.formatJson(filterVal, list);
            const name = this.date + '以来' + exportName
            export_json_to_excel(tHeader, data, name);
        },

        //导出的方法
        exportPRExcel(exportList, exportName) {
            console.log(exportList);
            const tHeader = ["org", "repo","prState", "prHtmlUrl", "prTitle","prCreateDate",]
            // 上面设置Excel的表格第一行的标题
            const filterVal = ["org", "repo","prState", "prHtmlUrl", "prTitle","prCreateDate",]
            // 上面的index、nickName、name是tableData里对象的属性
            const list = exportList; //把data里的tableData存到list
            const data = this.formatJson(filterVal, list);
            const name = this.date + '以来' + exportName
            export_json_to_excel(tHeader, data, name);
        },

        formatJson(filterVal, jsonData) {
            return jsonData.map(v => filterVal.map(j => v[j]));
        },
        exportExcelByGroup() {
            let result = this.commitList
            //获取数据长度，用于后期截取
            var length = result.length;
            var xlsxParam = {
                raw: true
            };
            let workbook = XLSX.utils.book_new();
            //每页放4W条数据，获取满页页数
            var fornum = parseInt(length / 40000);
            //获取剩余数据量
            var remainnum = length % 40000;
            //循环sheet页数开始填充
            for (var i = 0; i < fornum; i++) {
                let sheetdata = XLSX.utils.json_to_sheet(result.slice(0, 40000));
                //添加sheet页
                XLSX.utils.book_append_sheet(workbook, sheetdata, 'sheet' + (i + 1));
                result = result.slice(40000);
            }
            //最后剩余数据
            let last = XLSX.utils.json_to_sheet(result);
            XLSX.utils.book_append_sheet(workbook, last, 'sheet' + (fornum + 1));
            let wbout = XLSX.write(workbook, {
                bookType: 'xlsx',
                bookSST: true,
                type: 'array'
            });
            try {
                const name = this.date + '以来' + '所有commit数据.xlsx'
                FileSaver.saveAs(
                    new Blob([wbout], {
                        type: 'application/octet-stream;charset=utf-8"'
                    }), name);
            } catch (e) {
                if (typeof console !== 'undefined') console.error(e, wbout);
            }
        },
        importExcel(file) {
            this.$notify({
                title: '提示',
                message: '表格仅上传到浏览器，不会外传至服务器，为避免违规也可断网后进行上传过滤',
                duration: 0
            });
            this.readExcel(file.raw).then(res => {
                this.importExcelList = res;
                if (!this.importExcelList[0] || !this.importExcelList[0].committerEmail) {
                    this.$message.error("请确保表格格式正确，并且有committerEmail字段");
                }
            }).catch(err => {
                this.$message.error("读取过去数据Excel失败" + err);
                this.importExcelList = [];
            });
        },

        importDaChangList(file) {
            this.$notify({
                title: '提示',
                message: '表格仅上传到浏览器，不会外传至服务器，为避免违规也可断网后进行上传过滤',
                duration: 0
            });
            debugger
            this.readExcel(file.raw).then(res => {
                this.daChangList = res
            }).catch(err => {
                this.$message.error("读取大厂Excel失败" + err);
                this.daChangList = [];
            });
        },
        // 读取Excel文件
        readExcel(file) {
            return new Promise((resolve, reject) => {
                let reader = new FileReader();
                reader.readAsArrayBuffer(file);
                reader.onload = (e) => {
                    try {
                        let data = new Uint8Array(reader.result);
                        let workbook = XLSX.read(data, {
                            type: 'array'
                        });
                        let sheetName = workbook.SheetNames[0];
                        let worksheet = workbook.Sheets[sheetName];
                        let json = XLSX.utils.sheet_to_json(worksheet);
                        resolve(json);
                    } catch (error) {
                        reject(error);
                    }
                }
            });
        },
        filterImportExcelList() {
            this.filteredRepeatCommitterList = JSON.parse(JSON.stringify(this.repeatCommitterList))
            this.filteredKnowledgeCommitterList = JSON.parse(JSON.stringify(this.knowledgeCommitterList))
            this.filteredNoKnowledgeCommitterList = JSON.parse(JSON.stringify(this.noKnowledgeCommitterList))
            this.filteredOnlyKnowledgeCommitterList = JSON.parse(JSON.stringify(this.onlyKnowledgeCommitterList))
            this.filteredDaChangCommitterList = JSON.parse(JSON.stringify(this.daChangCommitterList))
            this.filteredAllCommitterList = JSON.parse(JSON.stringify(this.allCommitterList))

            this.importExcelList.forEach(item => {
                let email = item.committerEmail.toLowerCase();
                this.filteredAllCommitterList = this.filteredAllCommitterList.filter(v => {
                    return v.committerEmail.toLowerCase() != email;
                })
                this.filteredDaChangCommitterList = this.filteredDaChangCommitterList.filter(v => {
                    return v.committerEmail.toLowerCase() != email;
                })
                this.filteredRepeatCommitterList = this.filteredRepeatCommitterList.filter(v => {
                    return v.committerEmail.toLowerCase() != email;
                })
                this.filteredKnowledgeCommitterList = this.filteredKnowledgeCommitterList.filter(v => {
                    return v.committerEmail.toLowerCase() != email;
                })
                this.filteredNoKnowledgeCommitterList = this.filteredNoKnowledgeCommitterList.filter(v => {
                    return v.committerEmail.toLowerCase() != email;
                })
                this.filteredOnlyKnowledgeCommitterList = this.filteredOnlyKnowledgeCommitterList.filter(v => {
                    return v.committerEmail.toLowerCase() != email;
                })
            })
            console.log("filterImportExcelList success")
            this.$message.success('筛选成功');
        },
        getCommitter() {
            // 获取所有committer
            this.allCommitterList = [];
            this.allCommitterMap.forEach(v => {
                this.allCommitterList.push(v);
            });
            console.log('allCommitterList', this.allCommitterList);

            // 获取大厂committer
            this.daChangCommitterList = [];
            this.daChangCommitterMap.forEach(v => {
                this.daChangCommitterList.push(v);
            });
            console.log('daChangCommitterList', this.daChangCommitterList);

            // 获取既在白名单提交了又在其他仓库提交的committer
            this.repeatCommitterList = [];
            this.noKnowledgeCommitterMap.forEach((v, key) => {
                if (this.knowledgeCommitterMap.has(key)) {
                    this.repeatCommitterList.push(v);
                }
            });
            console.log('repeatCommitterList', this.repeatCommitterList);

            // 知识体系提交过的committer
            this.knowledgeCommitterList = [];
            this.knowledgeCommitterMap.forEach(v => {
                this.knowledgeCommitterList.push(v);
            });
            console.log('knowledgeCommitterList', this.knowledgeCommitterList);
            // 非知识体系提交过的committer
            this.noKnowledgeCommitterList = [];
            this.noKnowledgeCommitterMap.forEach(v => {
                this.noKnowledgeCommitterList.push(v);
            });
            console.log('noKnowledgeCommitterList', this.noKnowledgeCommitterList);

            // 获取只在知识体系提交过的committer
            this.onlyKnowledgeCommitterList = [];
            let repeatCommitterSet = new Set();
            this.repeatCommitterList.forEach(v => {
                repeatCommitterSet.add(v.committerEmail.toLowerCase());
            });
            console.log('repeatCommitterSet', repeatCommitterSet);
            console.log('knowledgeCommitterMap', this.knowledgeCommitterMap);
            this.knowledgeCommitterMap.forEach((v, key) => {
                if (!repeatCommitterSet.has(key)) {
                    this.onlyKnowledgeCommitterList.push(v);
                }
            });
            console.log('onlyKnowledgeCommitterList', this.onlyKnowledgeCommitterList);
        },
        getFilterEmailCommits() {
            if (!this.filterEmail || this.filterEmail.length == 0) {
                this.$message.warning("请输入邮箱")
                return
            }
            let email = this.filterEmail.toLowerCase()
            this.filterEmailCommits = this.commitList.filter(item => {
                if (item.committerEmail.toLowerCase() == 'noreply@gitee.com') {
                    return item.authorEmail.toLowerCase().includes(email)
                } else {
                    return item.committerEmail.toLowerCase().includes(email)
                }
            })
        },
        getFilterPRTitleCommits() {
            if (!this.filterPRTitle || this.filterPRTitle.length == 0) {
                this.$message.warning("请输入pr标题")
                return
            }
            let prTitle = this.filterPRTitle.toLowerCase()
            this.filterPRTitleCommits = this.commitList.filter(item => {
                return item.prTitle.toLowerCase().includes(prTitle)
            })
        },
        showFormula() {
            const confirmText = [
                'Sigs + Master +TPC 总数为集合A；',
                '　',
                '所有的仓库的贡献者  带50大企邮箱的  à 大厂共建  X；剩余部分为B；',
                '　',
                'B 中找出白名单仓库内的贡献者 = C；',
                '　',
                'C 在其他仓库也提交了代码的部分为重叠部分C1， 不重叠部分为 C2 = C-C1 (仅在知识体系工作组白名单中提交过代码，在其他仓库未提交代码)；',
                '　',
                '重叠部分的划分： C1 *1/2.5 =D1  归知识体系工作组  ； C1 *1.5/2.5 = D2  归活动与营销工作组；',
                '　',
                '知识体系组的总数 Y = C2 + D1；',
                '　',
                '活动与营销工作组的总数  Z = 总数 – X — Y；',
            ]
            const msg = []
            const h = this.$createElement
            for (const i in confirmText) {
                msg.push(h('p', null, confirmText[i]))
            }
            this.$confirm(
                '公式',
                {
                    title: '公式',
                    message: h('div', null, msg),
                    showCancelButton: true,
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'success'
                }
            )
        },
        showKPIData() {
            let x = this.daChangCommitterList.length
            let y = this.onlyKnowledgeCommitterList.length + this.repeatCommitterList.length / 2.5
            let z = this.allCommitterList.length - x - y
            const confirmText = [
                `大厂共建X = ${x}`,
                `知识体系组的总数Y = 仅在知识体系工作组白名单中提交过代码 +  重叠部分 *1/2.5 = ${y}`,
                `活动与营销工作组的总数Z = 总数 - X - Y = ${z}`,

            ]
            const msg = []
            const h = this.$createElement
            for (const i in confirmText) {
                msg.push(h('p', null, confirmText[i]))
            }
            this.$confirm(
                '各组数据',
                {
                    title: '各组数据',
                    message: h('div', null, msg),
                    showCancelButton: true,
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'success'
                }
            )
        },
        showKPIFilterData() {
            let x = this.filteredDaChangCommitterList.length
            let y = this.filteredOnlyKnowledgeCommitterList.length + this.filteredRepeatCommitterList.length / 2.5
            let z = this.filteredAllCommitterList.length - x - y
            const confirmText = [
                `大厂共建X = ${x}`,
                `知识体系组的总数Y = 仅在知识体系工作组白名单中提交过代码 +  重叠部分 *1/2.5 = ${y}`,
                `活动与营销工作组的总数Z = 总数 - X - Y = ${z}`,

            ]
            const msg = []
            const h = this.$createElement
            for (const i in confirmText) {
                msg.push(h('p', null, confirmText[i]))
            }
            this.$confirm(
                '各组数据',
                {
                    title: '各组数据',
                    message: h('div', null, msg),
                    showCancelButton: true,
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'success'
                }
            )
        }
    }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h1, h2 {
    font-weight: normal;
}

ul {
    list-style-type: none;
    padding: 0;
}

li {
    display: inline-block;
    margin: 0 10px;
}

a {
    color: #42b983;
}

.flex-row {
    display: flex;
    flex-direction: row;
    align-items: center;
    margin: 10px 0;
    /*flex-wrap: wrap;*/
}

.flex-between {
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: space-between;
    margin: 10px 0;
}

.body {
    width: 900px;
    margin: 0 auto;
}
</style>
